package com.ht.api.call.func.impl.wwx;

import java.util.stream.Collectors;

import javax.sql.DataSource;

import com.ht.api.bean.AjaxResult;
import com.ht.api.bean.LoginBean;
import com.ht.api.call.func.IFunctionCall;
import com.ht.api.db.Db;
import com.ht.api.db.Entity;
import com.ht.api.db.exception.HtException;
import com.ht.api.db.util.HtUtil;
import com.ht.api.open.OpenUtil;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
/**
 * 编辑获客链接
 * @author asq
 * @createTime 2025年1月13日 22:19:08
 */
@Slf4j
public class WwxCustomerLinkEditFunctionCall implements IFunctionCall {
	/** 接口ID：编辑获客链接 */
	private static final long API_ID = 1896834036354125824L;

	@Override
	public String getName() {
		return "编辑获客链接";
	}

	@Override
	public JSONObject execute(LoginBean me, JSONObject param, AjaxResult result) {
		// 获取登陆用户的数据源
		DataSource ds = me.getDataSource();
		
		// 验证参数
		HtUtil.checkParam(param, "main_id");
		JSONObject normalParam = HtUtil.revertJson(param);
		
		// 查询获客链接
		String mainId = normalParam.getStr("main_id");
		Entity wxCustomerLink = Db.createSqlParser("wx_customer_link").findById(ds, mainId);
		if (wxCustomerLink == null) {
			throw new HtException("获客链接不存在~");
		}
		String linkName = param.getStr("link_name");
		boolean hasRow = Db.createSqlParser("wx_customer_link").where("link_name", linkName)
				.where("main_id", "!=", mainId).hasRow(ds);
		if (hasRow) {
			throw new HtException("获客链接已存在：" + linkName);
		}
		
		// 如果获客链接有linkId字段，则需要调用企微接口
		boolean needSynWx = StrUtil.isNotBlank(wxCustomerLink.getStr("link_id"));
		if (needSynWx) {
			// 调用企微接口
			String appId = wxCustomerLink.getStr("appid");
			param.set("link_id", wxCustomerLink.getStr("link_id"));
			String str = OpenUtil.call(appId, API_ID, param);
			
			// 本地数据库
			JSONObject obj = JSONUtil.parseObj(str);
			if (obj.getInt("errcode") == 0) {
				edit(ds, wxCustomerLink, normalParam);
			} else {
				throw new HtException("企微接口返回错误：" + obj.getStr("errmsg"));
			}
		} else {
			edit(ds, wxCustomerLink, normalParam);
		}
		
		return JSONUtil.createObj();
	}

	/**
	 * 编辑获客链接
	 * @param ds 数据源
	 * @param wxCustomerLink 获客链接
	 * @param param 前端参数
	 */
	private void edit(DataSource ds, Entity wxCustomerLink, JSONObject param) {
		// 修改获客链接
		wxCustomerLink.set("link_name", param.getStr("link_name"));
		
		if (param.containsKey("skip_verify")) {
			wxCustomerLink.set("skip_verify", param.getBool("skip_verify") ? 1 : 0);
		}
		
		if (param.containsKey("priority_option")) {
			JSONObject priorityOption = param.getJSONObject("priority_option");
			wxCustomerLink.set("priority_type", priorityOption.getInt("priority_type"));
			
			JSONArray priorityUseridList = priorityOption.getJSONArray("priority_userid_list");
			wxCustomerLink.set("priority_userid_list", priorityUseridList.toString());
			if (!priorityUseridList.isEmpty()) {
				String hashCodes = priorityUseridList.stream().map(s -> String.valueOf(Math.abs(s.hashCode())))
						.collect(Collectors.joining(","));
				wxCustomerLink.set("priority_userid_list_hash", hashCodes);
			}
		}
		
		Db.insert(ds, wxCustomerLink);
	}
}
